package controller.filemanager;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import model.MediaProperty;
import model.MediaType;
import model.filemanager.FileManager;
import model.filemanager.MediaFile;



@SuppressWarnings("serial")
public class UpdateServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    	String key = req.getParameter("key");
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
    	FileManager fm = new FileManager(user.getEmail());
    	MediaFile mediaFile = null;
    	
    	try {
			mediaFile = fm.GetFile(req.getParameter("key"));
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	String type = mediaFile.getType();
    	Iterator<MediaProperty> props = MediaType.getMediaType(type).getAllMediaProperties().iterator(); 
 		MediaProperty prop;
 		while(props.hasNext()){
 			prop = props.next(); 
 			if(prop.editable){
 				String par = req.getParameter(prop.name);
 				if(par!=null && par!=""){
 					mediaFile.setProperty(prop.name, par);
 				}
 			}
 		}
 		
    	fm.UpdateFile(mediaFile);
    	
    	res.sendRedirect(req.getHeader("Referer"));
    }
}